// pages/testActivityList/index.js
Page({
  data: {
    envId: '',
    currentUser: '',
    activityList: [],
    selectedActivities: [],
    loading: false,
    claiming: false,
    deleting: false,
    availableCount: 0
  },

  onLoad() {
    // 获取全局配置
    const app = getApp();
    this.setData({
      envId: app.globalData.env || '未配置',
      currentUser: app.globalData.openid ? app.globalData.openid.substring(0, 8) + '...' : '未获取'
    });
  },

  // 获取活动列表
  async getActivityList() {
    this.setData({ loading: true });
    
    try {
      console.log('开始获取活动列表');
      
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'getActivityList'
        }
      });
      
      console.log('获取活动列表结果:', result);
      
             if (result.result && result.result.success) {
         const activityList = result.result.data || [];
         
         this.setData({
           activityList: activityList,
           availableCount: activityList.length // 后端只返回未领取的活动
         });
        
        wx.showToast({
          title: `获取成功，共${result.result.total}个活动`,
          icon: 'success'
        });
      } else {
        wx.showToast({
          title: result.result?.errMsg || '获取失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 复制活动信息到剪贴板
  copyActivityInfo(e) {
    const { index } = e.currentTarget.dataset;
    const activity = this.data.activityList[index];
    
    const activityInfo = JSON.stringify(activity, null, 2);
    
    wx.setClipboardData({
      data: activityInfo,
      success: () => {
        wx.showToast({
          title: '已复制到剪贴板',
          icon: 'success'
        });
      }
    });
  },

  // 选择活动
  selectActivity(e) {
    const { index } = e.currentTarget.dataset;
    const activity = this.data.activityList[index];
    
    // 如果已领取，不允许选择
    if (activity.hasClaimed) {
      wx.showToast({
        title: '已领取的活动不能重复选择',
        icon: 'none'
      });
      return;
    }
    
    const selectedActivities = [...this.data.selectedActivities];
    
    const activityIndex = selectedActivities.indexOf(activity._id);
    if (activityIndex > -1) {
      // 取消选择
      selectedActivities.splice(activityIndex, 1);
    } else {
      // 添加选择
      selectedActivities.push(activity._id);
    }
    
    this.setData({ selectedActivities });
  },

  // 全选可领取活动
  selectAllAvailable() {
    const availableActivities = this.data.activityList
      .filter(activity => !activity.hasClaimed)
      .map(activity => activity._id);
    
    this.setData({ selectedActivities: availableActivities });
    
    wx.showToast({
      title: `已选择 ${availableActivities.length} 个可领取活动`,
      icon: 'success'
    });
  },

  // 一键领取奖励
  async claimAllRewards() {
    if (this.data.selectedActivities.length === 0) {
      wx.showToast({
        title: '请先选择要领取的活动',
        icon: 'none'
      });
      return;
    }

    this.setData({ claiming: true });
    
    try {
      console.log('开始一键领取，活动ID:', this.data.selectedActivities);
      
      const result = await wx.cloud.callFunction({
        name: 'quickstartFunctions',
        data: {
          type: 'claimActivityReward',
          activityIds: this.data.selectedActivities
        }
      });
      
      console.log('一键领取结果:', result);
      
      if (result.result && result.result.success) {
        const { data } = result.result;
        
        // 计算积分和猎杀数的变化
        let pointsChange = 0;
        let killsChange = 0;
        
        if (data.addedItems && data.addedItems.length > 0) {
          const pointsItems = data.addedItems.filter(item => item.itemName === '积分');
          const killsItems = data.addedItems.filter(item => item.itemName === '猎杀数');
          
          pointsChange = pointsItems.reduce((sum, item) => sum + item.quantity, 0);
          killsChange = killsItems.reduce((sum, item) => sum + item.quantity, 0);
        }
        
        let content = `成功领取: ${data.totalClaimed}个\n失败: ${data.totalFailed}个`;
        
        if (pointsChange > 0) {
          content += `\n💰 积分增加: +${pointsChange}`;
        }
        
        if (killsChange > 0) {
          content += `\n🎯 猎杀数增加: +${killsChange}`;
        }
        
        content += '\n\n是否查看详细结果？';
        
        wx.showModal({
          title: '领取成功',
          content: content,
          confirmText: '查看详情',
          cancelText: '确定',
          success: (res) => {
            if (res.confirm) {
              // 显示详细结果
              let detailContent = '';
              
              if (data.claimedActivities.length > 0) {
                detailContent += '✅ 成功领取:\n';
                data.claimedActivities.forEach(activity => {
                  detailContent += `• ${activity.activityName}\n`;
                  activity.items.forEach(item => {
                    detailContent += `  - ${item.itemName} x${item.quantity}\n`;
                  });
                });
                
                // 显示积分和猎杀数的变化
                if (data.addedItems && data.addedItems.length > 0) {
                  const pointsItems = data.addedItems.filter(item => item.itemName === '积分');
                  const killsItems = data.addedItems.filter(item => item.itemName === '猎杀数');
                  
                  if (pointsItems.length > 0) {
                    const totalPoints = pointsItems.reduce((sum, item) => sum + item.quantity, 0);
                    detailContent += `\n💰 积分增加: +${totalPoints}\n`;
                  }
                  
                  if (killsItems.length > 0) {
                    const totalKills = killsItems.reduce((sum, item) => sum + item.quantity, 0);
                    detailContent += `🎯 猎杀数增加: +${totalKills}\n`;
                  }
                }
              }
              
              if (data.failedActivities.length > 0) {
                detailContent += '\n❌ 领取失败:\n';
                data.failedActivities.forEach(activity => {
                  detailContent += `• ${activity.activityId}: ${activity.reason}\n`;
                });
              }
              
              wx.showModal({
                title: '详细结果',
                content: detailContent,
                showCancel: false
              });
            }
          }
        });
        
                 // 重新获取活动列表以更新状态
         this.getActivityList();
         this.setData({ 
           selectedActivities: [],
           availableCount: 0
         });
        
      } else {
        wx.showToast({
          title: result.result?.errMsg || '领取失败',
          icon: 'error'
        });
      }
    } catch (error) {
      console.error('一键领取失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'error'
      });
    } finally {
      this.setData({ claiming: false });
    }
  },

  // 返回首页
  goBack() {
    wx.navigateBack();
  },

  // 删除已领取的活动
  async deleteClaimedActivities() {
    wx.showModal({
      title: '确认删除',
      content: '确定要删除所有已领取的活动吗？此操作不可恢复。',
      confirmText: '确定删除',
      cancelText: '取消',
      success: async (res) => {
        if (res.confirm) {
          this.setData({ deleting: true });
          
          try {
            const result = await wx.cloud.callFunction({
              name: 'quickstartFunctions',
              data: {
                type: 'deleteClaimedActivities'
              }
            });
            
            if (result.result && result.result.success) {
              const { data } = result.result;
              wx.showToast({
                title: data.message,
                icon: 'success'
              });
              
              // 重新获取活动列表
              this.getActivityList();
            } else {
              wx.showToast({
                title: result.result?.errMsg || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除已领取活动失败:', error);
            wx.showToast({
              title: '删除失败',
              icon: 'none'
            });
          } finally {
            this.setData({ deleting: false });
          }
        }
      }
    });
  }
}); 